package com.rzn.reading.service.impl;

import com.rzn.reading.BeanMapper;
import com.rzn.reading.BusinessException;
import com.rzn.reading.Message;
import com.rzn.reading.entity.Attach;
import com.rzn.reading.mapper.AttachMapper;
import com.rzn.reading.model.dto.AttachResultDTO;
import com.rzn.reading.model.param.UploadParam;
import com.rzn.reading.service.AttachService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.PutObjectRequest;

/**
 * <p>
 * 附件表 服务实现类
 * </p>
 *
 * @author rzn
 * @since 2022-02-12
 */
@Service
public class AttachServiceImpl implements AttachService {
    private final AttachMapper attachMapper;

    public AttachServiceImpl(AttachMapper attachMapper) {
        this.attachMapper = attachMapper;
    }

    @Override
    public AttachResultDTO upload(MultipartFile file,String ownerName, int ownerId,String category) {
        Attach attach = attachBuilder(file);
        attach.setOwnerId(ownerId);
        attach.setOwnerName(ownerName);
        attach.setCategory(category);
        int insert = attachMapper.insert(attach);
        if (insert != 1){
            throw new BusinessException(new Message("DB.ADD_FAILED","设备照片"));
        }
        return  BeanMapper.map(attach, AttachResultDTO.class);
    }

    @Override
    public List<AttachResultDTO> uploadBatch(MultipartFile[] files) {
        List<Attach> attaches = new ArrayList<>();
        for (MultipartFile file : files) {
            Attach attach = attachBuilder(file);
            attaches.add(attach);
        }
        int rows = attachMapper.insertBatch(attaches);
        return BeanMapper.mapList(attaches, AttachResultDTO.class);
    }

    @Override
    public int relateAttach(Integer ownerId, String ownerName, List<Integer> ids) {
        return attachMapper.relateAttach(ownerId,ownerName,ids);
    }

    @Override
    public List<Attach> findByOwner(Integer ownerId, String ownerName, String category) {
        return attachMapper.selectByOwner(ownerId,ownerName,category);
    }

    @Override
    public int removeByOwner(Integer ownerId, String ownerName, String category) {
        return attachMapper.deleteByOwner(ownerId,ownerName,category);
    }

    @Override
    public List<String> getUrls(String ownerName, Integer ownerId) {
        List<Attach> attach = attachMapper.selectByOwner(ownerId,ownerName, null);
        List<String> urls = attach.stream().map(Attach::getUrl).collect(Collectors.toList());
        return urls;
    }

    private String uploadOss(MultipartFile file) {
        // Endpoint以杭州为例，其它Region请按实际情况填写。
        String endpoint = AttachProperties.END_POINT;
        // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
        String accessKeyId = AttachProperties.ACCESS_KEY_ID;
        String accessKeySecret = AttachProperties.ACCESS_KEY_SECRET;
        String bucketName = AttachProperties.BUCKET_NAME;
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        String date = new DateTime().toString("yyyy/MM/dd");
        //唯一不重复id
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        //yyyy/MM/dd/uuid+文件的原始名字
        String name = date + "/" + uuid + file.getOriginalFilename();
        //文件输入流
        InputStream inputStream = null;

        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 创建PutObjectRequest对象。
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, name, inputStream);
        // 上传文件。
        ossClient.putObject(putObjectRequest);

        // 关闭OSSClient。
        ossClient.shutdown();

        return "https://" + bucketName + "." + endpoint + "/" + name;
    }

    private Attach attachBuilder(MultipartFile file) {
        Attach attach = new Attach();
        attach.setSize(file.getSize());
        String originalFilename = file.getOriginalFilename();
        attach.setName(originalFilename);
        assert originalFilename != null;
        attach.setExtension(originalFilename.substring(originalFilename.lastIndexOf(".")));
        attach.setUrl(uploadOss(file));
        return attach;
    }

    @Override
    public boolean removeById(Integer id) {
        //删除oss文件
        //删除数据库记录
        return attachMapper.deleteByPrimaryKey(id)==1;
    }
}
